<?php

namespace App\Http\Controllers\Innerend;


use App\Models\ArticleComment;
use App\Models\Fresh;
use App\Models\User;

class FreshController extends BaseController
{
    // 快讯
    public function initialize()
    {
        parent::initialize();

        $this->model = 'Fresh';
    }

    // 父级
    // 添加，修改，删除，列表，停用 操作


    // 列表数据展示
    protected function listTable($lists)
    {
        // 整理
        $trList = [];
        if(empty($lists)){
            return ['list' => $lists, 'tr' => $trList];
        }

        $userDb = new User();
        $uids   = array_column($lists, 'uid');
        $users  = $userDb->isCache(true)->getListInIds($uids);

        // 展示列表表格
        $listHtml = $this->adminList();
        foreach($lists as $key => $item){
            // 数据
            $_uid  = $item['uid'];
            $_user = $users[$_uid] ?? [];
            $_id   = $item['id'];
            //$status   = $item['status'] == 1 ? '正常' : '禁用';
            //$topOp  = $item['is_top'] == 1 ? '取消置顶' : '置顶';
            //$param  = ['id' => $_id, 'is_top' => 1 - $item['is_top']];
            $is_complain = $item['is_complain'] == 1 ? '是' : '否';

            // 操作
            //$operate = $listHtml->operate_status($param, $topOp, $item['is_top'], 'to-top');
            $operate = '';
            //$operate .= $listHtml->operate_edit(['id' => $_id], '编辑');
            $operate .= $listHtml->operate_soft_delete(['id' => $_id], '你确定要删除该文章吗？');

            // 页面
            $tr = $listHtml->list_check($item['id']);
            $tr .= $listHtml->list_td($item['title']);
            $tr .= $listHtml->list_td($_user['username']);
            $tr .= $listHtml->list_td($item['content']);
            $tr .= $listHtml->list_td($item['ip_address']);
            $tr .= $listHtml->list_td($item['read_no']);
            $tr .= $listHtml->list_td($item['comment_no']);
            $tr .= $listHtml->list_td($is_complain);
            $tr .= $listHtml->list_td(date('Y-m-d H:i', $item['ctime']));
            $tr .= $listHtml->list_td($operate);
            $tr .= $operate;

            // 整合
            $trList[] = $listHtml->list_tr($tr);
        }

        // 整合
        return ['list' => $lists, 'tr' => $trList];
    }

    // 列表字段
    protected function list_fields()
    {
        return ['title' => ['标题', 150], 'uid' => ['用户', 80], 'content' => '内容', 'ip_address' => '地址', 'read_no' => ['浏览数', 40], 'comment_no' => ['评论数', 40], 'is_complain' => ['是否投诉', 60], 'ctime' => ['创建时间', 120], 'operate' => ['操作', 250],];
    }

    // 表单页面
    protected function formTable()
    {
        $html = '';
        $info = $this->onShow();
        $form = $this->adminForm();

        // 默认一张图片
        if(empty($info['images'])){
            $_images = ["", "", ""];
        } else{
            $_images = json_decode($info['images'], true);
            $count   = count($_images);
            for($ii = 0; $ii < 3 - $count; $ii++){
                $_images[] = '';
            }
        }
        // 多个图片
        $images = '';
        foreach($_images as $image){
            $images .= $form->formShowImage($image);
        }

        $title       = $form->formInput('title', $info['title'] ?? '', '标题');
        $username    = $form->ajaxSearch('uid', $info['uid'] ?? '', 'User');
        $ip          = $form->formShow($info['ip'] ?? '127.0.0.1');
        $ip_address  = $form->formShow($info['ip_address'] ?? '本地');
        $content     = $form->formUeditor('content', $info['content'] ?? '');
        $is_complain = $form->formShow(empty($info['is_complain']) ? '否' : '是');
        $_id         = $form->formHidden('id', $info['id'] ?? '');

        $html .= $form->makeItem('标题', $title);
        $html .= $form->makeItem('编辑', $username);
        $html .= $form->makeItem('是否投诉', $is_complain);
        $html .= $form->makeItem('ip', $ip);
        $html .= $form->makeItem('地址', $ip_address);
        $html .= $form->makeItem('图片', $images);
        $html .= $form->makeItem('内容', $content);
        $html .= $_id;

        return $html;
    }


    // 删除（软删除）
    public function del()
    {
        $this->throwIf(empty($this->id), '请指定删除记录');

        $where  = ['id' => $this->id];
        $model  = $this->checkModel($this->model);
        $result = $model->isCache(true)->softDelete($where, ['verify' => -1]);
        $this->throwIf($result === false, $model->getError());

        return $this->success();
    }

    // 删除（软删除）
    public function delComment()
    {
        $ids = $this->getData('ids', [], 'is_array');
        $this->throwIf(empty($ids), '请指定删除记录!');
        $this->throwIf(count($ids) != count($ids, 1), '指定删除记录参数错误!');
        // 其他条件
        $fresh_id = $this->getData('fresh_id', 0, 'intval');
        $where    = ['channel' => 'fresh', 'article_id' => $fresh_id];
        $this->throwIf(empty($fresh_id), '请指定长短文编号!');

        $comment = new ArticleComment();
        $result  = $comment->isCache(true)->softDelete($where, $ids);
        $this->throwIf($result === false, $comment->getError());

        return $this->success();
    }

    // 快讯的评论
    public function comment()
    {
        $this->throwIf(empty($this->id), '请指定查看记录');
        $where   = ['article_id' => $this->id, 'channel' => 'fresh', 'verify' => 1]; // 'pid' => 0,
        $comment = new ArticleComment();
        $result  = $comment->listPage($where, $this->page, $this->rows);
        if($result['list']){
            $uids   = array_column($result['list'], 'uid');
            $userDb = new User();
            $types  = $this->userType(); // 认证类型
            $users  = $userDb->isCache(true)->getListInIds($uids);
            foreach($result['list'] as $key => $item){
                $_uid  = $item['uid'];
                $_info = $users[$_uid] ?? [];
                if($_info){
                    $_info['head_img']   = $this->getHeadImg($_info['head_img'] ?? '');
                    $_info['apply_type'] = $_info['is_apply'] == 1 ? ($types[$_info['apply_type']]['name'] ?? '') : '';
                    // $_info['apply_type'] = $types[$_info['apply_type']]['name'] ?? '';
                }

                // 整理
                $result['list'][$key]['user'] = $_info;
            }
        }

        return $this->success($result);
    }

    // 列表顶部按钮
    protected function listTopButton()
    {
        $addUrl     = url('/innerend/'.$this->controller.'/add');
        $top_button = '<a href="javascript:;" onclick="onEdit(\''.$addUrl.'\')" class="btn btn-success radius">添加</a> ';
        $this->assign('top_button', '');
    }

    // 发长短文
    public function publish()
    {
        $images     = $this->getData('images', [], 'is_array');
        $is_short   = $this->getData('is_short', 0, 'intval');
        $read_power = $this->getData('read_power', 0, 'intval');
        $is_draft   = $this->getData('is_draft', 0, 'intval');
        $uid        = $this->getData('uid', 0, 'intval');
        $title      = $this->getData('title', '', 'trim');
        $content    = $this->getData('content', '', 'trim');
        $this->throwIf(empty($content), '请填写转发内容!');
        $this->throwIf(is_null($is_short), '选择是长文还是短文!');
        $this->throwIf(empty($uid), '请选择发布的用户!');
        $this->throwIf(empty($is_short) && empty($title), '长文请填写标题!');

        // 发送消息的频率
        //$freshDb = new Fresh();
        //$where   = [["uid", '=', $this->myUid], ["ctime", '>', LARAVEL_TIME - 60 * 60]];
        //$nums    = $freshDb->where($where)->count();
        //$this->throwIf($nums >= 3, '你发送消息太频繁，请休息下再来！!');

        // 审核转发内容
        //$spam = antispam($content);
        //$this->throwIf(empty($spam), '含有不符合内容!!');

        // TODO 提取的话题与阿特的用户需要独立出来 （添加修改，与列表详情都需要使用）
        // TODO 提取阿特用户
        // TODO 提取话题
        // "<text data-id='143' data-type='1' class='test'>#测试话题#</text>";
        // 如果是草稿 则不提取，因为修改的时候不方便
        $freshData = $this->getData4Fresh($content, $is_draft);
        $uids      = $freshData['uids'];
        $topids    = $freshData['topids'];

        // TODO 提取图片
        if(empty($images)){
            $images = $this->getImage4content($content);
        }
        $this->throwIf(count($images) != count($images, 1), '请传递正确图片地址！');

        // 数据
        $ip   = $this->request->ip();
        $data = [
            'uid'        => $uid,
            'content'    => $content,
            'images'     => json_encode($images),
            'title'      => $title,
            'is_short'   => $is_short,
            'is_draft'   => $is_draft,
            'read_power' => $read_power,
            'ip'         => $ip,
            'ip_address' => $this->getIpAddress($ip),

            'parent_id'   => $this->getData("parent_id", 0, 'intval'),
            'news_id'     => $this->getData("news_id", 0, 'intval'),
            'dispatch_id' => $this->getData("dispatch_id", 0, 'intval'),
            'fangtan_id'  => $this->getData("fangtan_id", 0, 'intval'),
            'verify'      => 1,
        ];

        // 转发
        $fresh_id = 0;
        $channel  = '';
        $_isrelay = 0;
        if($data['parent_id']){
            $fresh_id = $data['parent_id'];
            $channel  = 'fresh';
            $_isrelay += 1;
        } elseif($data['news_id']){
            $fresh_id = $data['news_id'];
            $channel  = 'news';
            $_isrelay += 1;
        } elseif($data['dispatch_id']){
            $fresh_id = $data['dispatch_id'];
            $channel  = 'dispatch';
            $_isrelay += 1;
        }
        $this->throwIf($_isrelay > 1, '转发来源只能是新闻，快讯，长短文中的一种！');

        // TODO 审核
        $this->baiduTextCensor($title.$content);

        // 执行发布
        $freshDb = new Fresh();
        $id      = $freshDb->publish($uid, $data, $topids, $uids, $fresh_id, $channel);
        $this->throwIf($id === false, $freshDb->getError());
        // 获取金币
        if($is_short){
            $this->addGold('fresh_short', $uid);
        } else{
            $this->addGold('fresh_long', $uid);
        }

        return $this->success($id);
    }

    // 软删除
    public function onSoft()
    {
        $this->throwIf(empty($this->id), '请指定删除记录');

        $where  = ['id' => $this->id];
        $model  = $this->checkModel($this->model);
        $result = $model->isCache(true)->oneEdit($where, ['verify' => -1]);
        $this->throwIf($result === false, $model->getError());

        return $this->success();
    }

    // 修改长短文
    public function _onEdit()
    {
        $images     = $this->getData('images', [], 'is_array');
        $is_short   = $this->getData('is_short', 0, 'intval');
        $read_power = $this->getData('read_power', 0, 'intval');
        $is_draft   = $this->getData('is_draft', 0, 'intval');
        $uid        = $this->getData('uid', 0, 'intval');
        $title      = $this->getData('title', '', 'trim');
        $content    = $this->getData('content', '', 'trim');
        $this->throwIf(empty($this->id), '请填写修改记录的编号!');
        $this->throwIf(empty($content), '请填写转发内容!');
        $this->throwIf(is_null($is_short), '选择是长文还是短文!');
        $this->throwIf(empty($uid), '请选择发布的用户!');
        $this->throwIf(empty($is_short) && empty($title), '长文请填写标题!');

        // 发送消息的频率
        //$freshDb = new Fresh();
        //$where   = [["uid", '=', $this->myUid], ["ctime", '>', LARAVEL_TIME - 60 * 60]];
        //$nums    = $freshDb->where($where)->count();
        //$this->throwIf($nums >= 3, '你发送消息太频繁，请休息下再来！!');

        // 审核转发内容
        //$spam = antispam($content);
        //$this->throwIf(empty($spam), '含有不符合内容!!');

        // TODO 提取的话题与阿特的用户需要独立出来 （添加修改，与列表详情都需要使用）
        // TODO 提取阿特用户
        // TODO 提取话题
        // "<text data-id='143' data-type='1' class='test'>#测试话题#</text>";
        // 如果是草稿 则不提取，因为修改的时候不方便
        $freshData = $this->getData4Fresh($content, $is_draft);
        $uids      = $freshData['uids'];
        $topids    = $freshData['topids'];

        // TODO 提取图片
        if(empty($images)){
            $images = $this->getImage4content($content);
        }
        $this->throwIf(count($images) != count($images, 1), '请传递正确图片地址！');

        // 数据
        $data = [
            'id'         => $this->id,
            'uid'        => $uid,
            'content'    => $content,
            'images'     => json_encode($images),
            'title'      => $title,
            'is_short'   => $is_short,
            'is_draft'   => $is_draft,
            'read_power' => $read_power,
            'ip'         => $this->request->ip(),

            'parent_id'   => $this->getData("parent_id", 0, 'intval'),
            'news_id'     => $this->getData("news_id", 0, 'intval'),
            'dispatch_id' => $this->getData("dispatch_id", 0, 'intval'),
            'fangtan_id'  => $this->getData("fangtan_id", 0, 'intval'),
            'verify'      => 1,
            'is_complain' => 0,
        ];

        // 转发
        $fresh_id = 0;
        $channel  = '';
        $_isrelay = 0;
        if($data['parent_id']){
            $fresh_id = $data['parent_id'];
            $channel  = 'fresh';
            $_isrelay += 1;
        } elseif($data['news_id']){
            $fresh_id = $data['news_id'];
            $channel  = 'news';
            $_isrelay += 1;
        } elseif($data['dispatch_id']){
            $fresh_id = $data['dispatch_id'];
            $channel  = 'dispatch';
            $_isrelay += 1;
        }
        $this->throwIf($_isrelay > 1, '转发来源只能是新闻，快讯，长短文中的一种！');

        // TODO 审核
        $this->baiduTextCensor($title.$content);

        // 一些测试数据（测试后删除）
        //$topids   = [7, 8, 9];
        //$uids     = [7, 8, 9];

        // 执行修改
        $freshDb = new Fresh();
        $id      = $freshDb->onEdit($uid, $data, $topids, $uids, $fresh_id, $channel);
        $this->throwIf($id === false, $freshDb->getError());

        return $this->success($id);
    }

    // 列表查询
    protected function listWhere()
    {
        $where      = [['verify', '=', 1], ['fangtan_id', '=', 0],];
        $keyword    = $this->getData('keyword', null, 'trim');
        $uid        = $this->getData('uid', null, 'intval');
        $is_short   = $this->getData('is_short', null, 'intval');
        $start_time = $this->getData('start_time', null, 'intval');
        $end_time   = $this->getData('end_time', null, 'intval');
        if(!is_null($keyword)){
            $where[] = ['content', 'like', $keyword];
        }
        if(!is_null($is_short)){
            $where[] = ['is_short', '=', $is_short];
        }
        if(!is_null($uid)){
            $where[] = ['uid', '=', $uid];
        }
        if(!is_null($start_time)){
            $where[] = ['ctime', '>=', $start_time];
        }
        if(!is_null($end_time)){
            $where[] = ['ctime', '<=', $end_time];
        }

        return $where;
    }

    // 添加
    protected function _before_add()
    {
        $data = [
            // 'id'          => $this->getData("id", 0, 'intval'),
            // 'huida_id'    => $this->getData("huida_id", 0, 'intval'),
            // 'wenti_id'    => $this->getData("wenti_id", 0, 'intval'),
            // 'to_uid'      => $this->getData("to_uid", 0, 'intval'),
            // 'pic'         => $this->getData("pic", null, 'trim'),
            // 'read_no'    => $this->getData("read_no", 0, 'intval'),
            // 'virtual_no' => $this->getData("virtual_no", 0, 'intval'),
            // 'praise_no'  => $this->getData("praise_no", 0, 'intval'),
            // 'stamp_no'   => $this->getData("stamp_no", 0, 'intval'),
            // 'collect_no' => $this->getData("collect_no", 0, 'intval'),
            // 'comment_no' => $this->getData("comment_no", 0, 'intval'),
            // 'relay_no'   => $this->getData("relay_no", 0, 'intval'),

            'parent_id'   => $this->getData("parent_id", 0, 'intval'),
            'news_id'     => $this->getData("news_id", 0, 'intval'),
            'dispatch_id' => $this->getData("dispatch_id", 0, 'intval'),
            'fangtan_id'  => $this->getData("fangtan_id", 0, 'intval'),
            'uid'         => $this->getData("uid", 0, 'intval'),

            'title'      => $this->getData("title", null, 'trim'),
            'content'    => $this->getData("content", null, 'trim'),
            'ip'         => $this->request->ip(),
            'is_draft'   => $this->getData("is_draft", 0, 'intval'),
            'read_power' => $this->getData("read_power", 0, 'intval'),
            'is_short'   => $this->getData("is_short", 0, 'intval'),
            'verify'     => 1,
            // 'verify'     => $this->getData("verify", 0, 'intval'),  // TODO 百度审核
            // 'images'     => $this->getData("images", null, 'trim'),

            // 'itype'       => $this->getData("itype"),
            // 'url'         => $this->getData("url"),
            // 'is_complain' => $this->getData("is_complain", 0, 'intval'),
            // 'ctime'       => $this->getData("ctime", 0, 'intval'),
            // 'mtime'       => $this->getData("mtime", 0, 'intval'),
        ];

        // TODO 审核
        $this->baiduTextCensor($data);
        // TODO 提取图片
        $images = $this->getData("images", null, 'is_array');
        if(empty($images)){
            $images = $this->getImage4content($data['content']);
        }
        $data['images'] = json_encode($images);

        return $data;
    }

    // 修改
    protected function _before_edit()
    {
        $data = [
            'parent_id'   => $this->getData("parent_id", 0, 'intval'),
            'news_id'     => $this->getData("news_id", 0, 'intval'),
            'dispatch_id' => $this->getData("dispatch_id", 0, 'intval'),
            'fangtan_id'  => $this->getData("fangtan_id", 0, 'intval'),
            'uid'         => $this->getData("uid", 0, 'intval'),

            'title'      => $this->getData("title", null, 'trim'),
            'content'    => $this->getData("content", null, 'trim'),
            'ip'         => $this->request->ip(),
            'is_draft'   => $this->getData("is_draft", 0, 'intval'),
            'read_power' => $this->getData("read_power", 0, 'intval'),
            'is_short'   => $this->getData("is_short", 0, 'intval'),
            'verify'     => 1,
            // 'images'     => $this->getData("images", null, 'trim'),
            // 'verify'     => $this->getData("verify", 0, 'intval'),  // TODO 百度审核
        ];

        // TODO 审核
        $this->baiduTextCensor($data);
        // TODO 提取图片
        $images = $this->getData("images", null, 'is_array');
        if(empty($images)){
            $images = $this->getImage4content($data['content']);
        }
        $data['images'] = json_encode($images);

        return $data;
    }

}


